import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store/index';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/Home.vue'),
    redirect: '/home/welcome',
    children: [
      {
        path: 'welcome',
        name: 'welcome',
        component: () => import('../pages/Welcome.vue'),
        meta: {
          title: '公告主页',
        },
      },
      {
        path: 'dormitory',
        name: 'dormitory',
        component: () => import('../pages/Dormitory.vue'),
        meta: {
          title: '宿舍管理',
        },
      },
      {
        path: 'student',
        name: 'student',
        component: () => import('../pages/Student.vue'),
        meta: {
          title: '学生管理',
        },
      },
      {
        path: 'studentOwn',
        name: 'studentOwn',
        component: () => import('../pages/StudentOwn.vue'),
        meta: {
          title: '学生管理',
        },
      },
      {
        path: 'announcement',
        name: 'announcement',
        component: () => import('../pages/Announcement.vue'),
        meta: {
          title: '公告管理',
        },
      },
      {
        path: 'admin',
        name: 'admin',
        component: () => import('../pages/Admin.vue'),
        meta: {
          title: '管理员管理',
        },
      },
    ],
  },
];

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next();
  // const tokenStr = window.sessionStorage.getItem('token');
  // console.log(store.state.token);
  if (!store.state.token) return next('./login');
  // if (!tokenStr) return next('./login');
  next();
});

router.afterEach((to, from) => {
  document.title = to.meta.title || '宿舍管理系统';
});

export default router;
